// 引入用来发送请求的方法
import { request } from "../../request/index.js"

// pages/goods_detail/goods_detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    gooodsObj:{},
    isCollect:false
  },

  // 全局商品对象
  GoodsInfo:{},

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    let pages =  getCurrentPages();
    let currentPages=pages[pages.length-1]
     let options= currentPages.options

    const {goods_id} = options
    // console.log(goods_id)
    this.getDetailList(goods_id)
      
  },

  // 获取详情页面数据
  async getDetailList(goods_id){
    const gooodsObj= await request({url:"/goods/detail",data:{goods_id}})
    this.GoodsInfo = gooodsObj
    let collect=wx.getStorageSync("collect")||[];
    let isCollect = collect.some(v=>v.goods_id===this.GoodsInfo.goods_id)
    this.setData({
      isCollect,
      gooodsObj:{
        goods_name:gooodsObj.goods_name,
        goods_price:gooodsObj.goods_price,
        goods_introduce:gooodsObj.goods_introduce.replace(/\.webp/g,'.jpg'),
        pics:gooodsObj.pics
      }
    })
  },
  // 点击大图预览
  handlePrevewImage(e){
    // console.log("预览");
    const urls = this.GoodsInfo.pics.map(v=>v.pics_mid)
    console.log(e);
    const current=e.currentTarget.dataset.url
    wx.previewImage({
      current, // 当前显示图片的http链接
      urls // 需要预览的图片http链接列表
    })
  },
  // 点击加入购物车
  handleCartAdd(){
    // console.log("加入购物车");
    let cart = wx.getStorageSync("cart") || []
    let index = cart.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id)
    if(index===-1){
      // 不存在
      this.GoodsInfo.num=1
      this.GoodsInfo.checked=true
      cart.push(this.GoodsInfo)
    }else{
      // 存在
      cart[index].num++
    }
    wx.setStorageSync("cart",cart)
    wx.showToast({
      title: '加入成功',
      icon:"success",
      // 防止用户疯狂点击
      mask:true
    });
      
  },
  // 商品收藏
  handleCollect(){
    let isCollect=false
    let collect=wx.getStorageSync("collect")||[];
    let index =  collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id)
    if(index!==-1){
      collect.splice(index,1)
      isCollect=false
      wx.showToast({
        title: '取消成功',
        icon: 'success',
        mask: true
      });
        
    }else{
      collect.push(this.GoodsInfo)
      isCollect=true
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        mask: true
      });
    }
    wx.setStorageSync("collect", collect);
    this.setData({
      isCollect
    })
  }
})

